package com.xjscrm.console.service.customer.operatePlan.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.newcustmoerplan.SleepRule;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.common.vo.tasktagauto.Condition;
import com.xjscrm.common.vo.tasktagauto.EventRule;
import com.xjscrm.common.vo.tasktagauto.GroupSelect;
import com.xjscrm.common.vo.tasktagauto.ParaRule;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.operatePlan.*;
import com.xjscrm.console.param.wwCustomer.CustomerTagQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.operatePlan.AutoTagPlanService;
import com.xjscrm.console.service.customer.operatePlan.AutoTagTaskExcuteService;
import com.xjscrm.console.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AutoTagPlanServiceImpl implements AutoTagPlanService {

    @Autowired
    private AutoTagPlanServiceMapper autoTagPlanServiceMapper;

    @Autowired
    private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;

    @Autowired
    private WwTagsMapper wwTagsMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private DeviceGroupRelationMapper deviceGroupRelationMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private AutoTagTaskExcuteService autoTagTaskExcuteService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTaskTagAuto(TaskTagAutoDto taskTagAutoDto) {
        if(taskTagAutoDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(taskTagAutoDto.getName())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getParaType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getParaType()!=1&&taskTagAutoDto.getParaType()!=2){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()!=1&&taskTagAutoDto.getTagType()!=2){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()==1&&taskTagAutoDto.getEnterpriseType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        TaskTagAuto taskTagAuto=new TaskTagAuto();
        BeanUtil.copyProperties(taskTagAutoDto,taskTagAuto,"paraRule","eventRule");
        int time = DateUtil.getTime();
        taskTagAuto.setId(getSixDigitsNum());
        taskTagAuto.setCreateTime(time);
        taskTagAuto.setUpdateTime(time);

        if(taskTagAuto.getParaType()==1){
            if(taskTagAutoDto.getParaRule()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "条件触发，条件规则对象不能为空");
            }
            taskTagAuto.setParaRule(JSONObject.toJSONString(taskTagAutoDto.getParaRule()));
        }
        if(taskTagAuto.getParaType()==2){
            if(taskTagAutoDto.getEventRule()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "事件触发，事件规则对象不能为空");
            }
            taskTagAuto.setEventRule(JSONObject.toJSONString(taskTagAutoDto.getEventRule()));
        }

        if(taskTagAuto.getTagType()==1){
            if(taskTagAutoDto.getEnterpriseTags()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企微标签，必须传企微标签列表");
            }
            taskTagAuto.setEnterpriseTags(taskTagAutoDto.getEnterpriseTags().toString());
        }
        autoTagPlanServiceMapper.insertTaskTagAuto(taskTagAuto);


        if(taskTagAutoDto.getDeviceTagsRelList()!=null&&!taskTagAutoDto.getDeviceTagsRelList().isEmpty()){
            for (DeviceTagsRel deviceTagsRel :taskTagAutoDto.getDeviceTagsRelList()) {
                //若选择企业标签 的 全部机器人 不插入
                if(deviceTagsRel.getDeviceUniqueIds()!=null||!deviceTagsRel.getDeviceUniqueIds().isEmpty()){
                    //插入自动打标签方案和机器人关系
                    for (Long deviceUniqueId:deviceTagsRel.getDeviceUniqueIds()) {
                        TaskTagAutoDevice taskTagAutoDevice=new TaskTagAutoDevice();
                        taskTagAutoDevice.setMerId(taskTagAuto.getMerId());
                        taskTagAutoDevice.setTaskId(taskTagAuto.getId());
                        taskTagAutoDevice.setDeviceUniqueId(deviceUniqueId);
                        taskTagAutoDevice.setParaType(taskTagAuto.getParaType());
                        taskTagAutoDevice.setTagType(taskTagAuto.getTagType());
                        if(taskTagAutoDto.getTagType()==2){
                            if(deviceTagsRel.getPrivateTags()==null){
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人标签，必须传个人标签列表");
                            }
                            taskTagAutoDevice.setPrivateTags(deviceTagsRel.getPrivateTags().toString());
                        }
                        taskTagAutoDeviceMapper.addTaskTagAutoDevice(taskTagAutoDevice);
                    }
                }
            }
        }

        autoTagTaskExcuteService.ExcuteAutoTagTask(taskTagAuto);


    }


    @Override
    public Object getTaskTagAutoList(TaskTagAutoQuery taskTagAutoQuery) {
        if(taskTagAutoQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(taskTagAutoQuery.getOrderByField(), taskTagAutoQuery.isAsc());
        PageHelper.startPage(taskTagAutoQuery.getCurrent(),taskTagAutoQuery.getSize(),orderBy);
        List<TaskTagAutoVo> taskTagAutoVoList= autoTagPlanServiceMapper.getTaskTagAutoList(taskTagAutoQuery);

        MyPageInfo myPageInfo = new MyPageInfo<>(taskTagAutoVoList);
        return myPageInfo;
    }


    @Override
    public Object getTaskTagAutoDetail(TaskTagAutoDto taskTagAutoDto) {
        if(taskTagAutoDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagAutoDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        TaskTagAuto taskTagAuto= autoTagPlanServiceMapper.getById(taskTagAutoDto.getId(),taskTagAutoDto.getMerId());
        TaskTagAutoVo taskTagAutoVo = new TaskTagAutoVo();
        BeanUtil.copyProperties(taskTagAuto,taskTagAutoVo,"paraRule","eventRule");
        if(taskTagAuto.getParaType()==1){
            taskTagAutoVo.setParaRule(JSONObject.parseObject(taskTagAuto.getParaRule(),ParaRule.class));

            if(taskTagAutoVo.getParaRule()!=null&&taskTagAutoVo.getParaRule().getConditionList()!=null&&!taskTagAutoVo.getParaRule().getConditionList().isEmpty()){
                for (Condition condition:taskTagAutoVo.getParaRule().getConditionList()) {
                    if( condition.getGroupSelectList()!=null&&!condition.getGroupSelectList().isEmpty()){
                        for (GroupSelect groupSelect:condition.getGroupSelectList()) {
                            if(groupSelect.getGroupWxidList()!=null&&!groupSelect.getGroupWxidList().isEmpty()&&groupSelect.getDeviceId()!=null){
                                List<com.xjscrm.common.vo.tasktagauto.WwGroupVo> wwGroupList=new ArrayList<>();
                                for (String groupWxid:groupSelect.getGroupWxidList()) {
                                    WwGroup wwGroup = wwGroupMapper.getByGroupWxid(groupWxid, groupSelect.getDeviceId(), taskTagAutoDto.getMerId());
                                    if(wwGroup!=null){
                                        com.xjscrm.common.vo.tasktagauto.WwGroupVo wwGroupVo = new com.xjscrm.common.vo.tasktagauto.WwGroupVo();
                                        BeanUtil.copyProperties(wwGroup,wwGroupVo);
                                        WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());
                                        if(wwDevice!=null){
                                            wwGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                                            wwGroupVo.setDeviceName(wwDevice.getDeviceName());
                                        }
                                        wwGroupList.add(wwGroupVo);
                                    }
                                }
                                groupSelect.setWwGroupList(wwGroupList);
                            }
                        }
                    }
                }
            }
        }
        if(taskTagAuto.getParaType()==2){
            taskTagAutoVo.setEventRule(JSONObject.parseObject(taskTagAuto.getEventRule(), EventRule.class));

            if(taskTagAutoVo.getEventRule()!=null&&taskTagAutoVo.getEventRule().getGroupSelectList()!=null&&!taskTagAutoVo.getEventRule().getGroupSelectList().isEmpty()){
                        for (GroupSelect groupSelect:taskTagAutoVo.getEventRule().getGroupSelectList()) {
                            if(groupSelect.getGroupWxidList()!=null&&!groupSelect.getGroupWxidList().isEmpty()&&groupSelect.getDeviceId()!=null){
                                List<com.xjscrm.common.vo.tasktagauto.WwGroupVo> wwGroupList=new ArrayList<>();
                                for (String groupWxid:groupSelect.getGroupWxidList()) {
                                    WwGroup wwGroup = wwGroupMapper.getByGroupWxid(groupWxid, groupSelect.getDeviceId(), taskTagAutoDto.getMerId());
                                    if(wwGroup!=null){
                                        com.xjscrm.common.vo.tasktagauto.WwGroupVo wwGroupVo = new com.xjscrm.common.vo.tasktagauto.WwGroupVo();
                                        BeanUtil.copyProperties(wwGroup,wwGroupVo);
                                        WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());
                                        if(wwDevice!=null){
                                            wwGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                                            wwGroupVo.setDeviceName(wwDevice.getDeviceName());
                                        }
                                        wwGroupList.add(wwGroupVo);
                                    }
                                }
                                groupSelect.setWwGroupList(wwGroupList);
                            }
                        }
            }
        }
        //获取企业标签的标签列表
        List<DeviceTagsRel> deviceTagsRelList=new ArrayList<>();
                    if(taskTagAutoVo.getTagType()==1){
                        DeviceTagsRel deviceTagsRel = new DeviceTagsRel();
                        if(!StringUtils.isBlank(taskTagAuto.getEnterpriseTags())){
                            ObjectMapper objectMapper = new ObjectMapper();
                            List<Long>EnterpriseTags = null;
                            try {
                                EnterpriseTags = objectMapper.readValue(taskTagAuto.getEnterpriseTags(), List.class);
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }
                            CustomerTagQuery customerTagQuery=new CustomerTagQuery();
                            customerTagQuery.setMerId(taskTagAutoVo.getMerId());
                            customerTagQuery.setStatus(1);
                            customerTagQuery.setType(1);
                            customerTagQuery.setIfChild(1);
                            customerTagQuery.setTagIds(EnterpriseTags);
                            List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
                            List<String> EnterpriseTagNames=new ArrayList<>();
                            if(customerTag!=null&&!customerTag.isEmpty()){
                                customerTag.forEach(it->EnterpriseTagNames.add(it.getTagName()));
                            }
                            taskTagAutoVo.setEnterpriseTagNames(EnterpriseTagNames);
                            taskTagAutoVo.setEnterpriseTags(EnterpriseTags);
                        }

                        //获取所有机器人列表
                        if(taskTagAutoVo.getEnterpriseType()==0){
                            WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                            wwDeviceQuery.setMerId(wwDeviceQuery.getMerId());
                            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                            deviceTagsRel.setWwDeviceVoList(wwDeviceList);
                        }
                        //获取部分机器人列表
                        if(taskTagAutoVo.getEnterpriseType()==1){
                            TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
                            taskTagAutoDeviceQuery.setMerId(taskTagAutoVo.getMerId());
                            taskTagAutoDeviceQuery.setTaskId(taskTagAutoVo.getId());
                            List<TaskTagAutoDevice> taskTagAutoDeviceList=taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
                            List<Long> deviceUniqueIds=new ArrayList<>();
                            if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
                                taskTagAutoDeviceList.forEach(it->deviceUniqueIds.add(it.getDeviceUniqueId()));
                            }
                            if(deviceUniqueIds!=null&&!deviceUniqueIds.isEmpty()){
                                WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                                wwDeviceQuery.setMerId(taskTagAutoVo.getMerId());
                                wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                                List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                                deviceTagsRel.setWwDeviceVoList(wwDeviceList);
                            }
                        }
                        deviceTagsRelList.add(deviceTagsRel);
                    }

                    //获取个人标签的标签列表
                    if(taskTagAutoVo.getTagType()==2){
                        TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
                        taskTagAutoDeviceQuery.setMerId(taskTagAutoVo.getMerId());
                        taskTagAutoDeviceQuery.setTaskId(taskTagAutoVo.getId());
                        List<TaskTagAutoDevice> taskTagAutoDeviceList=taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
                        if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
                            for (TaskTagAutoDevice taskTagAutoDevice:taskTagAutoDeviceList) {
                                DeviceTagsRel deviceTagsRel = new DeviceTagsRel();


                                WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                                wwDeviceQuery.setMerId(taskTagAutoDevice.getMerId());
                                wwDeviceQuery.setDeviceUniqueIds(Arrays.asList(taskTagAutoDevice.getDeviceUniqueId()));
                                List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                                deviceTagsRel.setWwDeviceVoList(wwDeviceList);


                                String privateTags = taskTagAutoDevice.getPrivateTags();
                                ObjectMapper objectMapper = new ObjectMapper();
                                List<Long>tags = null;
                                try {
                                    tags = objectMapper.readValue(privateTags, List.class);
                                } catch (JsonProcessingException e) {
                                    throw new RuntimeException(e);
                                }
                                CustomerTagQuery customerTagQuery=new CustomerTagQuery();
                                customerTagQuery.setMerId(taskTagAutoVo.getMerId());
                                customerTagQuery.setStatus(1);
                                customerTagQuery.setType(2);
                                customerTagQuery.setIfChild(1);
                                customerTagQuery.setTagIds(tags);
                                List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
                                List<String> EnterpriseTagNames=new ArrayList<>();
                                if(customerTag!=null&&!customerTag.isEmpty()){
                                    customerTag.forEach(it->EnterpriseTagNames.add(it.getTagName()));
                                }
                                deviceTagsRel.setPrivateTagNames(EnterpriseTagNames);
                                deviceTagsRel.setPrivateTags(tags);
                                deviceTagsRelList.add(deviceTagsRel);
                            }
                            }
                    }
                         taskTagAutoVo.setDeviceTagsRelList(deviceTagsRelList);
                         return taskTagAutoVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTaskTagAuto(TaskTagAutoDto taskTagAutoDto) {
        if(taskTagAutoDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagAutoDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(StringUtils.isBlank(taskTagAutoDto.getName())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getParaType()!=1&&taskTagAutoDto.getParaType()!=2){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()!=1&&taskTagAutoDto.getTagType()!=2){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getTagType()==1&&taskTagAutoDto.getEnterpriseType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagAutoDto.getParaType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //修改自动打标签方案
        TaskTagAuto taskTagAuto=new TaskTagAuto();
        BeanUtil.copyProperties(taskTagAutoDto,taskTagAuto,"paraRule","eventRule");

        if(taskTagAuto.getParaType()==2){
            if(taskTagAutoDto.getEventRule()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "事件触发，事件规则对象不能为空");
            }
            taskTagAuto.setEventRule(JSONObject.toJSONString(taskTagAutoDto.getEventRule()));
        }

        if(taskTagAuto.getParaType()==1){
            if(taskTagAutoDto.getParaRule()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "条件触发，条件规则对象不能为空");
            }
            taskTagAuto.setParaRule(JSONObject.toJSONString(taskTagAutoDto.getParaRule()));
        }

        if(taskTagAuto.getTagType()==1){
            if(taskTagAutoDto.getEnterpriseTags()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企微标签，必须传企微标签列表");
            }
            taskTagAuto.setEnterpriseTags(taskTagAutoDto.getEnterpriseTags().toString());
        }
        taskTagAuto.setStatus(0);
        autoTagPlanServiceMapper.updateTaskTagAuto(taskTagAuto);


        //查询所有的自动打标签方案和机器人关系 删除
        TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
        taskTagAutoDeviceQuery.setMerId(taskTagAutoDto.getMerId());
        taskTagAutoDeviceQuery.setTaskId(taskTagAutoDto.getId());
        List<TaskTagAutoDevice> taskTagAutoDeviceList = taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
        if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
            for (TaskTagAutoDevice taskTagAutoDevice:taskTagAutoDeviceList) {
                taskTagAutoDeviceMapper.deleById(taskTagAutoDevice.getId(),taskTagAutoDevice.getMerId());
            }
        }


        //若选择企业标签 的 全部机器人 不插入
        if(taskTagAutoDto.getDeviceTagsRelList()!=null&&!taskTagAutoDto.getDeviceTagsRelList().isEmpty()){
            for (DeviceTagsRel deviceTagsRel :taskTagAutoDto.getDeviceTagsRelList()) {
                //若选择企业标签 的 全部机器人 不插入
                if(deviceTagsRel.getDeviceUniqueIds()!=null||!deviceTagsRel.getDeviceUniqueIds().isEmpty()){
                    //插入自动打标签方案和机器人关系
                    for (Long deviceUniqueId:deviceTagsRel.getDeviceUniqueIds()) {
                        TaskTagAutoDevice taskTagAutoDevice=new TaskTagAutoDevice();
                        taskTagAutoDevice.setMerId(taskTagAuto.getMerId());
                        taskTagAutoDevice.setTaskId(taskTagAuto.getId());
                        taskTagAutoDevice.setDeviceUniqueId(deviceUniqueId);
                        taskTagAutoDevice.setParaType(taskTagAuto.getParaType());
                        taskTagAutoDevice.setTagType(taskTagAuto.getTagType());
                        if(taskTagAutoDto.getTagType()==2){
                            if(deviceTagsRel.getPrivateTags()==null){
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人标签，必须传个人标签列表");
                            }
                            taskTagAutoDevice.setPrivateTags(deviceTagsRel.getPrivateTags().toString());
                        }
                        taskTagAutoDeviceMapper.addTaskTagAutoDevice(taskTagAutoDevice);
                    }
                }
            }
        }

        autoTagTaskExcuteService.ExcuteAutoTagTask(taskTagAuto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleTaskTagAuto(TaskTagAutoDto taskTagAutoDto) {
        if(taskTagAutoDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagAutoDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        TaskTagAuto taskTagAuto=autoTagPlanServiceMapper.getById(taskTagAutoDto.getId(),taskTagAutoDto.getMerId());
        if(taskTagAuto==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }
        //删除方案
        autoTagPlanServiceMapper.deleById(taskTagAuto.getId(),taskTagAuto.getMerId());

        //删除方案和机器人关系
        TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
        taskTagAutoDeviceQuery.setTaskId(taskTagAuto.getId());
        taskTagAutoDeviceQuery.setMerId(taskTagAuto.getMerId());
        List<TaskTagAutoDevice> taskTagAutoDeviceList = taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);
        if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
            for (TaskTagAutoDevice taskTagAutoDevice:taskTagAutoDeviceList) {
                taskTagAutoDeviceMapper.deleById(taskTagAutoDevice.getId(),taskTagAutoDevice.getMerId());
            }
        }

    }


    @Override
    public Object getTaskTagAutoDeviceList(TaskTagAutoDeviceListQuery taskTagAutoDeviceListQuery) {
        if(taskTagAutoDeviceListQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagAutoDeviceListQuery.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        //先查询出方案
        TaskTagAuto taskTagAuto = autoTagPlanServiceMapper.getById(taskTagAutoDeviceListQuery.getId(), taskTagAutoDeviceListQuery.getMerId());

        if(taskTagAuto==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "方案不存在");
        }
        TaskTagAutoDeviceQuery taskTagAutoDeviceQuery=new TaskTagAutoDeviceQuery();
        taskTagAutoDeviceQuery.setMerId(taskTagAutoDeviceListQuery.getMerId());

        List<Long> duviceUniqueId=new ArrayList<>();

        List<Long> getDeviceUniqueIds=new ArrayList<>();
        if(!StringUtils.isBlank(taskTagAutoDeviceListQuery.getKeyword())){
               //机器人ID
               WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
               wwDeviceQuery.setMerId(taskTagAutoDeviceListQuery.getMerId());
               wwDeviceQuery.setKeyword(taskTagAutoDeviceListQuery.getKeyword());
               List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
               if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                   wwDeviceList.forEach(it->getDeviceUniqueIds.add(it.getId()));
               }
               if(getDeviceUniqueIds.isEmpty()){
                   return new MyPageInfo<>(null);
               }
        }

         List<Long> groupDeviceUniqueIds=new ArrayList<>();
        if(taskTagAutoDeviceListQuery.getDeviceGroupId()!=null){
            DeviceGroupRelationQuery deviceGroupRelationQuery=new DeviceGroupRelationQuery();
            deviceGroupRelationQuery.setMerId(taskTagAutoDeviceListQuery.getMerId());
            deviceGroupRelationQuery.setGroupId(taskTagAutoDeviceListQuery.getDeviceGroupId());
            List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
            if(deviceGroupRelationList!=null&&!deviceGroupRelationList.isEmpty()){
                groupDeviceUniqueIds = deviceGroupRelationList.stream().map(DeviceGroupRelation::getDeviceUniqueId).distinct().collect(Collectors.toList());
            }
            if(groupDeviceUniqueIds.isEmpty()){
                return new MyPageInfo<>(null);
            }
        }

        if(!getDeviceUniqueIds.isEmpty()&&groupDeviceUniqueIds.isEmpty()){
            duviceUniqueId=getDeviceUniqueIds;
        }
        if(getDeviceUniqueIds.isEmpty()&&!groupDeviceUniqueIds.isEmpty()){
            duviceUniqueId=groupDeviceUniqueIds;
        }
        if(!getDeviceUniqueIds.isEmpty()&&!groupDeviceUniqueIds.isEmpty()){
            //获取交集
            duviceUniqueId = getDeviceUniqueIds.stream().filter(groupDeviceUniqueIds::contains).collect(Collectors.toList());
        }


        if(!duviceUniqueId.isEmpty()){
            taskTagAutoDeviceQuery.setDeviceUniqueIds(duviceUniqueId);
        }

        if(taskTagAuto.getTagType()==1&&taskTagAuto.getEnterpriseType()==0){
            taskTagAutoDeviceQuery.setCondition("outer");
        }else {
            taskTagAutoDeviceQuery.setCondition("left");
        }
        taskTagAutoDeviceQuery.setTaskId(taskTagAuto.getId());

        String orderBy = OrderByUtil.getOrderBy(taskTagAutoDeviceListQuery.getOrderByField(), taskTagAutoDeviceListQuery.isAsc());
        PageHelper.startPage(taskTagAutoDeviceListQuery.getCurrent(),taskTagAutoDeviceListQuery.getSize(),orderBy);
        List<TaskTagAutoDeviceVo> taskTagAutoDeviceList = taskTagAutoDeviceMapper.getTaskTagAutoDeviceList(taskTagAutoDeviceQuery);
        if(taskTagAutoDeviceList!=null&&!taskTagAutoDeviceList.isEmpty()){
            taskTagAutoDeviceList.forEach(it->it.setSleepRule(JSONObject.parseObject(it.getRule(), OperatorPlanDeviceRule.class)));
        }

        MyPageInfo<TaskTagAutoDeviceVo> taskTagAutoDeviceVoMyPageInfo = new MyPageInfo<>(taskTagAutoDeviceList);

        if(taskTagAutoDeviceVoMyPageInfo.getRecords()!=null&&!taskTagAutoDeviceVoMyPageInfo.getRecords().isEmpty()){
            for (TaskTagAutoDeviceVo taskTagAutoDeviceVo:taskTagAutoDeviceVoMyPageInfo.getRecords()) {
                if(taskTagAutoDeviceVo.getCreateTime()==null){
                    taskTagAutoDeviceVo.setCreateTime(taskTagAuto.getCreateTime());
                }
            }
        }
        return taskTagAutoDeviceVoMyPageInfo;
    }


    @Override
    public void updateTaskTagAutoDevice(TaskTagAutoDeviceDto taskTagAutoDeviceDto) {
        if(taskTagAutoDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
//        if(taskTagAutoDeviceDto.getDeviceUniqueId()==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
//        }
        if(taskTagAutoDeviceDto.getTaskId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        TaskTagAuto taskTagAuto = autoTagPlanServiceMapper.getById(taskTagAutoDeviceDto.getTaskId(), taskTagAutoDeviceDto.getMerId());

        if(taskTagAuto==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }
        //新增规则
        if(taskTagAutoDeviceDto.getId()==null){
            TaskTagAutoDevice taskTagAutoDevice=new TaskTagAutoDevice();
            taskTagAutoDevice.setMerId(taskTagAuto.getMerId());
            taskTagAutoDevice.setTaskId(taskTagAuto.getId());
            taskTagAutoDevice.setDeviceUniqueId(taskTagAutoDeviceDto.getDeviceUniqueId());
            taskTagAutoDevice.setParaType(taskTagAuto.getParaType());
            taskTagAutoDevice.setTagType(taskTagAuto.getTagType());
            taskTagAutoDevice.setRule(JSONObject.toJSONString(taskTagAutoDeviceDto.getSleepRule()));
            taskTagAutoDeviceMapper.addTaskTagAutoDevice(taskTagAutoDevice);
        }

        //修改规则
        if(taskTagAutoDeviceDto.getId()!=null){
          TaskTagAutoDevice taskTagAutoDevice = taskTagAutoDeviceMapper.getById(taskTagAutoDeviceDto.getId(),taskTagAutoDeviceDto.getMerId());
            taskTagAutoDevice.setRule(JSONObject.toJSONString(taskTagAutoDeviceDto.getSleepRule()));
            taskTagAutoDeviceMapper.updateTaskTagAutoDevice(taskTagAutoDevice);
        }

    }

    @Override
    public void batchdeleTaskTagAutoDevice(BatchdeleTaskTagAutoDeviceDto batchdeleTaskTagAutoDeviceDto) {
        if(batchdeleTaskTagAutoDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchdeleTaskTagAutoDeviceDto.getIds()==null||batchdeleTaskTagAutoDeviceDto.getIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        for (Long id:batchdeleTaskTagAutoDeviceDto.getIds()) {
            batchdeleTaskTagAutoDeviceDto.setId(id);
            deleTaskTagAutoDevice(batchdeleTaskTagAutoDeviceDto);
        }
    }

    @Override
    public void batchUpdateTaskTagAutoDeviceSleepRule(BatchUpdateTaskTagAutoDeviceDto batchUpdateTaskTagAutoDeviceDto) {
        if(batchUpdateTaskTagAutoDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchUpdateTaskTagAutoDeviceDto.getUpdateTaskTagAutoDevice()==null||batchUpdateTaskTagAutoDeviceDto.getUpdateTaskTagAutoDevice().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

            for (UpdateTaskTagAutoDevice updateTaskTagAutoDevice:batchUpdateTaskTagAutoDeviceDto.getUpdateTaskTagAutoDevice()) {
                TaskTagAutoDeviceDto taskTagAutoDeviceDto=new TaskTagAutoDeviceDto();
                taskTagAutoDeviceDto.setId(updateTaskTagAutoDevice.getId());
                taskTagAutoDeviceDto.setMerId(batchUpdateTaskTagAutoDeviceDto.getMerId());
                taskTagAutoDeviceDto.setTaskId(updateTaskTagAutoDevice.getTaskId());
                taskTagAutoDeviceDto.setSleepRule(batchUpdateTaskTagAutoDeviceDto.getSleepRule());
                taskTagAutoDeviceDto.setDeviceUniqueId(updateTaskTagAutoDevice.getDeviceUniqueId());
                updateTaskTagAutoDevice(taskTagAutoDeviceDto);
            }
    }


    private void deleTaskTagAutoDevice(BatchdeleTaskTagAutoDeviceDto batchdeleTaskTagAutoDeviceDto) {
        if(batchdeleTaskTagAutoDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchdeleTaskTagAutoDeviceDto.getIds()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        //删除
        taskTagAutoDeviceMapper.deleById(batchdeleTaskTagAutoDeviceDto.getId(),batchdeleTaskTagAutoDeviceDto.getMerId());
    }

    private Long getSixDigitsNum(){
         return  (long) ((Math.random() * 9 + 1) * 100000);
    }
}
